import Vue from 'vue'
import axios from 'axios'
import merge from 'lodash/merge'
import router from '@/router'
import { Notification } from 'element-ui'
import HttpData from './HttpData'

// axios.defaults.withCredentials = true
const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
  },
  baseURL: (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl)
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  config.headers['tenantId'] = -2

  if (!(config.data instanceof FormData)) {
    let data = config.data || {}
    let httpData = new HttpData(data)
    config.data = httpData.getWrapData()
  } else {
    config.params = {
      'token': Vue.cookie.get('admintoken') || ''
    }
  }
  return config
}, error => {
  // clearLoginInfo()
  // router.push({ name: 'login' })
  return Promise.reject(error)
})
http.interceptors.response.use(response => {
  if (response.config.responseType === 'blob') {
    return response
  }
  // if(response)
  if (response.status === 401 || parseInt(response.data.code) === 401) {
    // clearLoginInfo()
    router.push({ name: 'login' })
    // return false
  } else if (response.status !== 200 || parseInt(response.data.code) !== 200) {
    Notification.error({
      customClass: 'global_notify',
      title: '错误',
      message: response.data.msg
    })
  }
  return response.data
}, error => {
  if (error.response.status === 401) {
    // clearLoginInfo()
    router.push({ name: 'login' })
  }
  return Promise.reject(error)
})

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

export default http
